<template>
    <div id="home" v-if="showPage">
        <div v-if="metaId === 'mindMap'">
            <div class="title-wrap">
                <div class="title-text">
                    <img src="../assets/img/mindMap_icon.png" alt="" />
                    <span>思维导图</span>
                </div>
                <div class="title-btns">
                    <img src="../assets/img/mini-w.png" @click="$electron.ipcRenderer.send('resource-window-minimize',{metaId:metaId})" alt="" />
                    <img src="../assets/img/close-w.png" @click="$electron.ipcRenderer.send('close-resource-window',{metaId:metaId})" alt="" />
                </div>
            </div>
        </div>
        <div v-if="metaId !== 'mindMap'" class="top flex-center" style="-webkit-app-region: drag;-webkit-user-select: none;">
            <!-- <div class="desktopCapturer"  @click.passive="captureScreen">生成截图</div> -->
            {{title}}
            <div class="top-handle flex-around" style="-webkit-app-region: no-drag;">
                <img src="../assets/img/mini.png" alt="" class="pointer"
                    @click="$electron.ipcRenderer.send('resource-window-minimize',{metaId:metaId})">
                <div class="pointer" v-if="res_type == 7 || res_type == 18"  @click="toMax">
                    <img style="width:15px;height:15px;transform:translateY(2px)" src="../assets/img/large-w.png" alt="" v-if="isMax">
                    <img style="width:15px;height:15px;transform:translateY(2px)" src="../assets/img/normal-w.png" alt="" v-if="!isMax">
                </div>
                <img src="../assets/img/close.png" alt="" class="pointer"
                    @click="$electron.ipcRenderer.send('close-resource-window',{metaId:metaId})">
            </div>
        </div>
        <transition name="classfiy">
            <router-view></router-view>
        </transition>
        <div v-if="res_type !==7 && res_type !== 18"  class="align-center tool-container" id="introBox">
            <div :class="['pointer', 'align-start','toolactive', active?'tool-animation-a':'tool-animation-na']"
                ref="toolkit">
                <img src="../assets/img/menu.png" alt="" style="margin-top:20px" @click="showIntro">
                <img src="../assets/img/close-circle.png"
                    @click="$electron.ipcRenderer.send('close-resource-window',{metaId:metaId})" alt=""
                    style="margin-top:14px">
            </div>
            <div class="bottom-toolkit align-center pointer" @click="showToolkit">
                <img src="../assets/img/active.png" alt="" v-if="active">
                <img src="../assets/img/resource-toolkit.png" alt="" v-else>
            </div>
        </div>
        <div v-if="res_type == 7"  class="align-center video_tool-container">
            <div :class="['pointer', 'align-start','toolactive', active?'video_tool-animation-a':'video_tool-animation-na']"
                ref="toolkit">
                <img src="../assets/img/menu.png" alt="" style="margin-top:20px" @click="showIntro">
                <div class="pointer" v-if="res_type ==7 "  style="margin-top:10px" @click="toMax">
                    <img src="../assets/img/menu_max.png" alt="" v-if="!isMax">
                    <img src="../assets/img/menu_max.png" alt="" v-if="isMax">
                </div>
                <img src="../assets/img/close-circle.png"
                    @click="$electron.ipcRenderer.send('close-resource-window',{metaId:metaId})" alt=""
                    style="margin-top:6px;margin-bottom:8px">
            </div>
            <div class="bottom-toolkit align-center pointer" @click="showToolkit">
                <img src="../assets/img/active.png" alt="" v-if="active">
                <img src="../assets/img/resource-toolkit.png" alt="" v-else>
            </div>
        </div>
        <div v-if="res_type == 18" class="align-center bosvideo_tool-container">
            <div :class="['pointer', 'align-start','toolactive', active?'video_tool-animation-a':'video_tool-animation-na']"
                ref="toolkit">
                <img src="../assets/img/menu.png" alt="" style="margin-top:20px" @click="showIntro">
                <div class="pointer" v-if="res_type == 18"  style="margin-top:10px" @click="toMax">
                    <img src="../assets/img/menu_max.png" alt="" v-if="!isMax">
                    <img src="../assets/img/menu_max.png" alt="" v-if="isMax">
                </div>
                <img src="../assets/img/close-circle.png"
                    @click="$electron.ipcRenderer.send('close-resource-window',{metaId:metaId})" alt=""
                    style="margin-top:6px;margin-bottom:8px">
            </div>
            <div class="bosvideo_bottom-toolkit align-center pointer" @click="showToolkit">
                <img src="../assets/img/active.png" alt="" v-if="active">
                <img src="../assets/img/resource-toolkit.png" alt="" v-else>
            </div>
        </div>
        <div class="intro align-center" v-if="introSign">
            <div class="close-inter pointer" @click="showIntro">
                <i class="el-icon-close"></i>
            </div>
            <div class="title">简介</div>
            <el-divider></el-divider>
            {{intro.trim()?intro:'暂无简介'}}
        </div>
    </div>
</template>
<script>
const { screen , dialog } = require('electron').remote
// 获取屏幕尺寸
    function getSize() {
    // scaleFactor 缩放因子
    const { size, scaleFactor } = screen.getPrimaryDisplay();
    console.log('size',size,scaleFactor);
    return {
        width: size.width * scaleFactor,
        height: size.height * scaleFactor
    }
}
// const psList = require('ps-list')
import bus from '../utils/bus.js'
import { SqlLib } from '../../../../static/lib/sqlite/SqlLib';
import { UrlUtil } from '../../../../static/utils/UrlUtil';
import { UserResource } from '../../../../static/lib/sqlite/model/UserResource';
import { collectUserPoint } from '../api/point'
// import userApi from '../../content/api/user.js'
const remote = require('electron').remote
let startTime = null
const channelMap = {
    resOurces: 3,
    mindMap: 4,
    charts: 5,
    extractNumber: 6,
    countDown: 7,
    Quiz: 8,
    tProgress: 9,
}
export default {
    name: "HomePage",
    data () {
        return {
            active: false,
            title: '',
            metaId: '',
            userId: '',
            lessonId: '',
            onlinePPtId:'',
            res_type:'',
            intro: '',
            introSign: false,
            loadingMask: null,
            showPage: false,
            isMax: false,
        }
    },
    mounted () {
        bus.$on('hideIntro',(msg)=>{
            if (msg == true) {
                document.getElementById('introBox').style.display = "none"
            }else{
                document.getElementById('introBox').style.display = ""
            }
        })
        console.log('homePage')
        if (UrlUtil.getQueryString('metaId')) {
            this.metaId = UrlUtil.getQueryString('metaId')
            this.userId = UrlUtil.getQueryString('userId')
            this.lessonId = UrlUtil.getQueryString('lessonId')
            this.bookId = UrlUtil.getQueryString('bookId')
            
            this.goCorrespondingResource()
            return
        }
        remote.getCurrentWindow().on('close', () => {
            if (startTime) {
                let time = parseInt(((new Date - startTime)/60000).toFixed())
                // if (time < 1) return
                if (time < 1) {
                    time = 1
                }
                const setRecordTime = new BroadcastChannel('record-time')
                setRecordTime.postMessage({
                    metaId: this.metaId,
                    playTime: time > 5 ? 5 : time,
                    startTime: startTime
                })
            }
        })

        this.$electron.ipcRenderer.on('sendMessage', (event, message) => {
            this.userId = message.userId
            this.lessonId = message.lessonId
            this.metaId = message.metaId
            this.bookId = message.bookId
            this.res_type = message.res_type
            this.onlinePPtId = message.onlinePPtId
            this.pptType = message.pptType
            console.log('message',message);
        })
        // this.$emit('installPageMessage')

    },
    watch: {
        metaId (nval) {
            if (['tProgress', 'countDown','extractNumber', 'charts', 'mindMap', 'Preview', 'Picture','recognize','onlinePPT'].includes(nval)) {
                this.$nextTick(() => {
                    let dom = document.getElementById('downloadmask')
                    if (dom) {
                        document.body.removeChild(dom)
                    }
                })
            }
            this.goCorrespondingResource()
        },
    },
    methods: {
        async captureScreen() {
            const url_base64 = await this.getCaptureBySourceThumbnail();
            return url_base64;
        },
        async getCaptureBySourceThumbnail() {
            console.log('desktopCapturer 捕捉屏幕');
            let screenImg = document.getElementsByClassName('desktopCapturer')
            console.log('screenImg-----',screenImg);
            screenImg[0].style.opacity = '0'
            const { desktopCapturer } = require('electron')
            const sources = await desktopCapturer.getSources({
                types: ['window', 'screen'],
                thumbnailSize: getSize()
            });
            if (!sources || !sources.length){
                screenImg[0].style.opacity = '1'
                throw new Error('sources 为空');
            }
            
            sources.forEach(item => {
                if (item.name === "美丽科学") {
                    console.log('item.thumbnail.toDataURL()',item.thumbnail.toDataURL());
                    let base64 = item.thumbnail.toDataURL().replace(/^data:image\/\w+;base64,/, "");
                    let dataBuffer = new Buffer(base64, 'base64');
                    let dia = dialog.showSaveDialog({
                        title: "保存",
                        filters: [{name: "IMG", extensions: ['png', 'jpg']}],
                        defaultPath: '资源截图',
                    })
                    const fs = require('fs')
                    screenImg[0].style.opacity = '1'
                    let _this = this
                    fs.writeFile(dia, dataBuffer, function (err) {
                        if (err) {
                            console.log(err)
                        } else {
                            _this.$message.success('保存成功')
                        }
                    })
                }
            });
        },
       
        goCorrespondingResource () {
            startTime = new Date()
            let userId = this.userId
            let metaId = this.metaId
            let lessonId = this.lessonId
            let userResource = new UserResource();
            let bsr = null
            if (lessonId && metaId) {
                userResource.lessonId = lessonId
                userResource.userId = userId
                userResource.resourceId = metaId
                let bsrArry = SqlLib.getInstance(window.$DBDIR).selectAllObjectByKeys(userResource, ["lessonId", "userId", "resourceId"])
                bsr = (bsrArry && bsrArry[0]) ? JSON.parse(bsrArry[0].resourceDescription) : null
            }
            let channelType = ''
            if (bsr && bsr.meta_info && bsr.meta_info.meta_type) {
                if (bsr.meta_info.meta_type === 'Quiz') channelType = 'Quiz'
                else channelType = 'resOurces'
            } else {
                channelType = metaId
            }
            
            collectUserPoint({ channel: channelMap[channelType] }).then(res => console.log(res))
            //调试代码
            if (metaId === 'countDown') {
                let win = this.$electron.remote.getCurrentWindow();
                let webFrame = this.$electron.webFrame
                webFrame.setZoomFactor(win.getSize()[0] / 1440)
                this.$router.push({ name: 'countDown' });
                return
            }
            // if (metaId === 'mini') {
            //     let win = this.$electron.remote.getCurrentWindow();
            //     let webFrame = this.$electron.webFrame
            //     webFrame.setZoomFactor(win.getSize()[0] / 1440)
            //     this.$router.push({ name:'mini' });
            //     return
            // }
            if (metaId === "extractNumber") {
                let win = this.$electron.remote.getCurrentWindow();
                let webFrame = this.$electron.webFrame
                webFrame.setZoomFactor(win.getSize()[0] / 1440)
                this.$router.push({ name: 'extractNumber' });
                return
            }
            if (metaId === "tProgress") {
                let win = this.$electron.remote.getCurrentWindow();
                let webFrame = this.$electron.webFrame
                webFrame.setZoomFactor(win.getSize()[0] / 1440)
                this.$router.push({ name: 'tProgress' })
                return
            }

            if (metaId === 'Picture') {
                let win = this.$electron.remote.getCurrentWindow();
                let webFrame = this.$electron.webFrame
                webFrame.setZoomFactor(win.getSize()[0] / 1440)
                this.$router.push({ name: 'Picture' })
                return
            }
            if (metaId === 'recognize') {
                let win = this.$electron.remote.getCurrentWindow();
                let webFrame = this.$electron.webFrame
                webFrame.setZoomFactor(win.getSize()[0] / 1440)
                this.$router.push({ name: 'recognize',params: { lessonId:lessonId }  })
                return
            }
            if (metaId === 'onlinePPT') {
                let win = this.$electron.remote.getCurrentWindow();
                let webFrame = this.$electron.webFrame
                webFrame.setZoomFactor(win.getSize()[0] / 1440)
                this.$router.push({ name: 'onlinePPT',params: { lessonId:lessonId,onlinePPtId: this.onlinePPtId,pptType: this.pptType }  })
                return
            }
            this.showPage = true
            if (metaId === 'charts') {
                //调试代码
                this.title = '图表工具'
                this.$router.push({ name: 'charts' })
                return
            }
            if (metaId === 'Preview') {
                //调试代码
                this.title = '图片预览'
                this.$router.push({ name: 'Preview' })
                return
            }
            if (metaId === 'mindMap') {
                //调试代码
                this.title = '思维导图'
                this.$router.push({ name: 'MindMap', params: { lessonId: lessonId } })
                return
            }

            if (bsr) {
                const name = bsr.meta_info ? bsr.meta_info.meta_type : bsr.downloadInfo.FileType
                this.title = bsr.meta_info ? bsr.meta_info.name : bsr.name
                this.intro = bsr.intro
                // localStorage.setItem('bsr', JSON.stringify(bsr))
                if (this.$route.fullPath === ('/HomePage/' + name)) return

                startTime = new Date()
                this.$nextTick(() => this.$router.push({ name: name, params: { bsr, userId, metaId } }))
            }
        },
        toMax () {
            this.isMax = !this.isMax;
            if (this.isMax) {
                // console.log(this.$electron);
                this.$electron.ipcRenderer.send('resource-window-normalmize',{metaId:this.metaId});
            } else {
                this.$electron.ipcRenderer.send('resource-window-maximize',{metaId:this.metaId});
            }
        },
        showIntro () {
            this.introSign = !this.introSign
        },
        showToolkit () {
            this.active = !this.active
        },
    }
}



</script>

<style lang="scss">
.classfiy-enter-active,
.classfiy-leave-active {
    transition: all 0.5s linear;
}
.classfiy-enter,
.classfiy-leave-to {
    transform: translateY(-10px);
    opacity: 0;
}
.desktopCapturer{
    position: absolute;
    left: 0px;
    top:  0px;
    // transform: translateY(30px);
    width: 90px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    font-size: 16px;
    border-radius: 4px;
    background-color: rgb(197, 194, 194);
    cursor: pointer;
    z-index: 99999;
    -webkit-app-region: no-drag;
}
#home {
    .title-wrap {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 64px;
        background-image: url("../assets/img/title_bg.png");
        background-size: cover;
        -webkit-app-region: drag;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 30px;
        box-sizing: border-box;
        z-index: 98;
        .title-text {
          display: flex;
          align-items: center;
            img{
                margin-right: 8px;
                width: 20px;
                height: 20px;
            }
            span {
                font-size: 18px;
                color: #fff;
            }
        }
        .title-btns {
          -webkit-app-region: no-drag;
            img {
                width: 14px;
                height: 14px;
                margin-left: 18px;
                cursor: pointer;
            }
        }
    }
    .intro {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background-color: rgba(240, 248, 254, 1);
        color: #333;
        width: 400px;
        border-radius: 8px;
        padding: 20px;
        font-size: 14px;
        z-index: 1024;
        .title {
            font-size: 20px;
            font-weight: 500;
            color: #000;
        }
        .close-inter {
            position: absolute;
            top: 10px;
            right: 10px;
        }
    }
    .top {
        height: 30px;
        width: 100%;
        background: rgba(240, 248, 254, 1);
        box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.12);
        position: relative;
        .top-handle {
            position: absolute;
            top: 5px;
            right: 10px;
            width: 60px;
        }
        img {
            width: 14px;
            height: 14px;
        }
    }
    .tool-container {
        position: fixed;
        bottom: 75px;
        right: 22px;
        width: 60px;
        z-index: 2048;
    }
    .bosvideo_tool-container{
        position: fixed;
        bottom: 75px;
        right: 22px;
        width: 60px;
        height: 180px;
        z-index: 2048;
    }
    .video_tool-container{
        position: fixed;
        bottom: 75px;
        right: 22px;
        width: 60px;
        height: 180px;
        z-index: 2048;
    }
    .bosvideo_bottom-toolkit{
        position: fixed;
        bottom: 75px;
        right: 22px;
        z-index: 100;
        img {
            width: 60px;
            height: 60px;
        }
    }
    .bottom-toolkit {
        position: fixed;
        bottom: 75px;
        right: 22px;
        z-index: 100;
        img {
            width: 60px;
            height: 60px;
        }
    }
    .toolactive {
        background-image: url(../assets/img/toolkit-bg.png);
        background-size: 100% 100%;
        height: 0;
        width: 48px;
        opacity: 0;
        overflow: hidden;
        img {
            width: 24px;
            height: 24px;
        }
    }
    .tool-animation-a {
        animation: showheight 1s ease forwards;
    }
    .tool-animation-na {
        animation: hiddenheight 1s ease forwards;
    }
    .video_tool-animation-a{
        animation: showvideoheight 1s ease forwards;
    }
     .video_tool-animation-na {
         animation: hiddenvideoheight 1s ease forwards;
     }
    @keyframes showheight {
        form {
            height: 0;
        }
        to {
            opacity: 1;
            height: 150px;
        }
    }
    @keyframes hiddenheight {
        form {
            height: 150px;
        }
        to {
            height: 0;
        }
    }
    @keyframes showvideoheight {
        form {
            height: 0;
        }
        to {
            opacity: 1;
            height: 210px;
        }
    }
    @keyframes hiddenvideoheight {
        form {
            height: 210px;
        }
        to {
            height: 0;
        }
    }
}
</style>
